import axios from 'axios';
import { throwErr, fromDataTrim, alertMessage, urlencode } from './myUtil';
axios.interceptors.request.use(
  config => {
    config.timeout = 15 * 1000;// 请求响应时间;
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200 || response.status === 201) {
      return Promise.resolve(response.data);
    } else {
      alertMessage(response.data.title,'warning')
      return Promise.reject(response.data)
    }
  },
  error => {
    if (error && error.response) {
      let res = {}
      res.code = error.response.status
      res.msg = throwErr(error.response.status, error.response) // throwErr 捕捉服务端的http状态码 定义在utils工具类的方法
      alertMessage(res.msg,'warning')
      return Promise.reject(res)
    }
    let tip = error.message;
    if (error.message === 'Network Error') tip = '网络错误，请稍后再试';
    if (error.message.indexOf('timeout') !== -1) tip = '请求超时，请稍后再试';
    alertMessage(tip,'warning');
    return Promise.reject(error)
  }
);
// --------暴露 request API 管理--------
export default function request(params) {
  let data = params.data;
  const url = params.url;
  const BASEURL = params.baseUrl;
  const dataType = params.dataType || 'json';
  const method = params.method.toLocaleLowerCase();
  const headers = { 'content-type': "application/json;charset=utf-8"};
  if (dataType === 'fromData') {
    data = fromDataTrim(data);
    headers['content-type'] = 'multipart/form-data';
  }
  // 发送请求 封装 RESTful API的各种请求方式
  switch (method) {
    case "put":
      return axios.put(url, data,{ headers, baseURL: BASEURL });
    case "post":
     return axios.post(url, data,{ headers, baseURL: BASEURL });
     case "delete":
      return axios.delete(url, { headers, params: data, baseURL: BASEURL });
    case "posturl":
      return axios.post(url + '?' + urlencode(data),{ headers, baseURL: BASEURL });
    case "getblob":
      // 导出数据必须返回类型改为blob
      return axios.get(url, { params: data, headers, baseURL: BASEURL, responseType:'blob' });
    default:
      return axios.get(url, { params: data, headers, baseURL: BASEURL});
  }
}